package com.taotie.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taotie.constant.MessageConstant;
import com.taotie.dto.UserLoginDTO;
import com.taotie.entity.User;
import com.taotie.exception.LoginFailedException;
import com.taotie.mapper.UserMapper;
import com.taotie.properties.WeChatProperties;
import com.taotie.service.UserService;
import com.taotie.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    //微信登陆凭证校验地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;


    /**
     * 根据微信授权码实现微信登陆
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String code = userLoginDTO.getCode();
        String openid = getOpenid(code);
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        User user = userMapper.getByOpenid(openid);

        //如果user为空则为该用户注册
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        return user;
    }


    // 获取openId的公共方法
    private String getOpenid(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        //authorization_code为授权选项，此处只需填写这个值
        map.put("grant_type", "authorization_code");
        //调用HttpClientUtil向微信发送get请求
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        log.info("微信登陆返回结果:{}", json);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        log.info("微信用户的openid:{}", openid);
        return openid;

    }
}
